package handler

import (
	"context"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"mxshop_srvs/userop_srv/model"
	proto "mxshop_srvs/userop_srv/proto/gen/v1"
)

func MsgModelToPb(m model.LeavingMessages) *proto.MessageEntity {
	return &proto.MessageEntity{
		Id: int32(m.ID),
		Message: &proto.Message{
			UserId:      m.UserID,
			MessageType: proto.MsgType(m.MessageType),
			Subject:     m.Subject,
			Message:     m.Message,
			File:        m.File,
		},
	}
}

func (s *Service) MessageList(_ context.Context, req *proto.MessageListRequest) (*proto.MessageListResponse, error) {
	messages, err := s.DB.GetMessages(req)
	if err != nil {
		return nil, status.Error(codes.Internal, "")
	}

	data := make([]*proto.MessageEntity, 0, len(messages))
	for _, m := range messages {
		data = append(data, MsgModelToPb(m))
	}

	return &proto.MessageListResponse{
		Total:    int32(len(data)),
		Messages: data,
	}, nil
}

func (s *Service) CreateMessage(_ context.Context, req *proto.Message) (*proto.MessageEntity, error) {
	ID, err := s.DB.CreateMessage(req)
	if err != nil {
		return nil, status.Error(codes.Internal, "")
	}
	return &proto.MessageEntity{
		Id:      int32(ID),
		Message: req,
	}, nil
}
